<template>
  <div>
    <h1>双向拖拽分组</h1>

    <div class="groupDiv">
      <ul id="leftGroup" @dragover="dragoverOfLeftGroup" @drop="dropOfLeftGroup">
        <!-- $event可以获取事件 -->
        <li v-for="item in leftGroupList" :key="item" draggable="true" @dragstart="dragstartOfLeftGroup($event, item)">
          item{{item}}
        </li>
        <li>我是感知释放后的位置</li>
      </ul>

      <ul id="rightGroup" @dragover="dragoverOfRightGroup" @drop="dropOfRightGroup">
        <li v-for="item in rightGroupList" :key="item" draggable="true" @dragstart="dragstartOfRightGroup($event, item)">
          item{{item}}
        </li>
      </ul>
    </div>
  </div>

</template>

<script>
export default {
  data () {
    return {
      leftGroupList: [],
      rightGroupList: []
    }
  },
  created () {
    let leftGroupList = [];
    for (let i = 0; i < 10; i++) {
      leftGroupList.push(i + "")
    }
    this.leftGroupList = leftGroupList;
  },
  methods: {
    /** 开始拖拽 可拖动元素时触发 */
    dragstartOfLeftGroup (dragEvent, item) {
      let dataTransfer = dragEvent.dataTransfer;
      dataTransfer.setData('type', 'left2Right');
      dataTransfer.setData('dragItem', item);
    },
    /** 在容器中 拖拽 可拖动元素过程中触发 */
    dragoverOfLeftGroup (dragEvent) {
      dragEvent.preventDefault();
    },
    /** 在容器中，拖拽释放 可拖动元素时触发 */
    dropOfLeftGroup (dragEvent) {
      let dataTransfer = dragEvent.dataTransfer;
      if (dataTransfer.getData('type') != 'right2Left') {
        // 防止从left分组拖回left分组
        return;
      }
      let dragItem = dataTransfer.getData('dragItem');
      this.rightGroupList.splice(this.rightGroupList.indexOf(dragItem), 1);
      this.leftGroupList.push(dragItem)
    },
    /** 开始拖拽 可拖动元素时触发 */
    dragstartOfRightGroup (dragEvent, item) {
      let dataTransfer = dragEvent.dataTransfer;
      dataTransfer.setData('type', 'right2Left');
      dataTransfer.setData('dragItem', item);
    },
    /** 在容器中 拖拽 可拖动元素过程中触发 */
    dragoverOfRightGroup (dragEvent) {
      dragEvent.preventDefault();
    },
    /** 在容器中，拖拽释放 可拖动元素时触发 */
    dropOfRightGroup (dragEvent) {
      let dataTransfer = dragEvent.dataTransfer;
      if (dataTransfer.getData('type') != 'left2Right') {
        // 防止从right分组拖回right分组
        return;
      }
      let dragItem = dataTransfer.getData('dragItem');
      this.leftGroupList.splice(this.leftGroupList.indexOf(dragItem), 1);
      this.rightGroupList.push(dragItem)
    },

  }

}
</script>

<style lang="less" scoped>
.groupDiv {
  display: flex;
  ul {
    flex-grow: 1;
  }
  #leftGroup {
    background-color: coral;
  }
  #rightGroup {
    background-color: grey;
  }
}
</style>>